package com.logos.ruralrevitalization.utils;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.logos.ruralrevitalization.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Date;

//@Component
@Slf4j
//@ConditionalOnProperty(prefix = "rural.jwt", name = "enabled", havingValue = "true")
public class JwtTool {

    @Value("${rural.jwt.key}")
    private String key;

    private JWTSigner jwtSigner;
    @PostConstruct
    public void init() {
        if (key == null || key.isEmpty()) {
            throw new IllegalArgumentException("JWT密钥不能为空，请检查配置文件");
        }
        this.jwtSigner = JWTSignerUtil.createSigner("HS256", key.getBytes());
    }

    /**
     * 创建 access-token
     *
     * @param userId 用户手机号
     * @param ttl   token有效期
     * @return access-token
     */

    public String createToken(String userId, Duration ttl) {
        long issuedAt = System.currentTimeMillis();
        long expiresAt = issuedAt + ttl.toMillis();
        log.info("Creating token with issued-at: {}, expires-at: {}", issuedAt, expiresAt);
        return JWT.create()
                .setPayload("user-id", userId)
                .setPayload("issued-at", String.valueOf(issuedAt)) // 添加时间戳
                .setExpiresAt(new Date(expiresAt)) // 确保使用毫秒时间戳
                .setSigner(jwtSigner)
                .sign();
    }
//    public String createToken(String userId, Duration ttl) {
//        return JWT.create()
//                .setPayload("user-id", userId)
//                .setPayload("issued-at", String.valueOf(System.currentTimeMillis())) // 添加时间戳
//                .setExpiresAt(new Date(System.currentTimeMillis() + ttl.toMillis())) // 确保使用毫秒时间戳
//                .setSigner(jwtSigner)
//                .sign();
//    }


    /**
     * 解析token
     *
     * @param token token字符串
     * @return 解析刷新token得到的用户信息
     */
    public String parseToken(String token) {
        if (token == null || token.isEmpty()) {
            throw new UnauthorizedException("未登录");
        }

        try {
            JWT jwt = JWT.of(token).setSigner(jwtSigner);
            log.info("Token issued-at: {}, expires-at: {}, current time: {}",
                    jwt.getPayload("issued-at"), jwt.getPayload("exp"), System.currentTimeMillis());
            if (!jwt.verify()) {
                log.info("jwt.verify.error.token:{}", token);
                throw new UnauthorizedException("无效的token");
            }
            JWTValidator.of(jwt).validateDate();

            Object userPayload = jwt.getPayload("user-id");
            if (userPayload == null) {
                throw new UnauthorizedException("无效的token");
            }

            log.info("jwt.parse.success.token:{}", token);
            return userPayload.toString();
        } catch (ValidateException e) {
            log.error("Token已经过期: {}", e.getMessage());
            throw new UnauthorizedException("token已经过期");
        } catch (RuntimeException e) {
            log.error("Token无效: {}", e.getMessage());
            throw new UnauthorizedException("无效的token");
        }


/*        try {
            JWT jwt = JWT.of(token).setSigner(jwtSigner);
            log.info("Token issued-at: {}, current time: {}", jwt.getPayload("issued-at"), System.currentTimeMillis());
            if (!jwt.verify()) {
                log.info("jwt.verify.error.token:{}",token);
                throw new UnauthorizedException("无效的token");
            }
            JWTValidator.of(jwt).validateDate();

            Object userPayload = jwt.getPayload("user-id");
            if (userPayload == null) {
                throw new UnauthorizedException("无效的token");
            }

            log.info("jwt.parse.success.token:{}",token);
            return userPayload.toString();
        } catch (ValidateException e) {
            throw new UnauthorizedException("token已经过期");
        } catch (RuntimeException e) {
            throw new UnauthorizedException("无效的token");
        }*/

    }
};